#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: announcements.py
@time: 2025/8/19  10:03
# @describe:
"""
from flask import Blueprint, request, jsonify, current_app
from flask_login import login_required, current_user
from models.announcement import AnnouncementManager

announcement_bp = Blueprint('announcements', __name__)
announcement_manager = AnnouncementManager()


@announcement_bp.route('/api/announcements', methods=['GET'])
def get_announcements():
    announcements = announcement_manager.get_all()
    return jsonify({
        'success': True,
        'data': announcements
    })


@announcement_bp.route('/api/announcements', methods=['POST'])
@login_required
def create_announcement():
    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权操作'}), 403

    data = request.get_json()
    if not data or not data.get('title') or not data.get('content'):
        return jsonify({'success': False, 'message': '标题和内容不能为空'}), 400

    try:
        new_announcement = announcement_manager.create(
            title=data['title'],
            content=data['content'],
            user_id=current_user.id
        )
        return jsonify({
            'success': True,
            'message': '公告发布成功',
            'data': new_announcement
        })
    except Exception as e:
        current_app.logger.error(f'创建公告失败: {str(e)}')
        return jsonify({'success': False, 'message': '发布失败'}), 500


@announcement_bp.route('/api/announcements/<announcement_id>', methods=['DELETE'])
@login_required
def delete_announcement(announcement_id):
    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权操作'}), 403

    success = announcement_manager.delete(announcement_id)
    if not success:
        return jsonify({'success': False, 'message': '公告不存在'}), 404

    return jsonify({'success': True, 'message': '公告删除成功'})